<template>
    <div class="collectRead">
        <div class="intelligent-container">
            <div class="intelligent-train">
                <div class="w1200 intelligent-train-header mb20" :style="{padding:haveCollect?'0 40px 0 160px':'0'}">{{ title }}
                    <i v-if="haveCollect" @click="readCollect"
                        :class="[defaultStart ? 'el-icon-star-on' : 'el-icon-star-off']"
                        style="color: rgb(241, 209, 149); cursor: pointer;"></i>
                    <span v-if="haveCollect">
                        <el-button v-if="!paperData.isAnswer" style="float: right;margin-top: 22px;"
                            class="button button-bg-second" @click="submitPaper">交卷</el-button>
                        <el-button v-else style="float: right;margin-top: 22px;" class="button button-bg-second"
                            @click="nextQuestion">下一题</el-button>
                    </span>
                </div>
                <div v-if="haveCollect" class="intelligent-train-contain-box">
                    <div class="intelligent-train-contain w1200">
                        <ReadingQuestion :paperData="paperData"></ReadingQuestion>
                    </div>
                </div>
                <el-card v-if="!haveCollect" class="w1200" shadow="never"
                    style="border-radius: 12px;text-align: center;padding: 40px 0;">
                    <img src="@/assets/img/no-question.png" alt="" />
                    <p class="no-text">暂无收藏</p>
                </el-card>
                <div v-if="haveCollect" class="w1200 mt10">
                    <el-pagination :style="{ float: 'right' }"
                        @current-change="handleCurrentChange" :current-page.sync="currentPage" :page-size="1"
                        layout="total, prev, pager, next" :total="total">
                    </el-pagination>
                </div>
            </div>
        </div>
        <div @click="openDrawer" class="mosk-btn">题目类型选择</div>
        <el-drawer title="题目类型选择" :visible.sync="drawer" direction="rtl" :wrapperClosable="false" :modal="false"
            :show-close="false">
            <span class="mosk-drawer-close" @click="drawer = false"><i class="el-icon-arrow-right"></i></span>
            <el-form ref="studentForm" :model="readForm" label-width="80px">
                <!-- 题目来源 -->
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="题目来源:">
                            <el-radio-group v-model="readForm.source_type">
                                <el-radio-button :label="5">全部</el-radio-button>
                                <el-radio-button :label="1">智能训练</el-radio-button>
                                <el-radio-button :label="2">水平测试</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 时间范围 -->
                <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="时间范围:">
                            <el-date-picker v-model="readForm.dataTime" value-format="timestamp" type="daterange"
                                align="right" unlink-panels range-separator="至" start-placeholder="开始日期"
                                end-placeholder="结束日期" :picker-options="pickerOptions">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 单词组选择 -->
                <!-- <el-row :gutter="24">
                    <el-col :span="22">
                        <el-form-item label="词组选择:">
                            <el-select v-model="readForm.unit_id" placeholder="请选择">
                                <el-option v-for="item in elementOptions" :key="item.unit_id" :label="item.unit_name"
                                    :value="item.unit_id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row> -->
            </el-form>
        </el-drawer>
    </div>
</template>

<script>
import ReadingQuestion from "../../read/components/readingQuestion";
import { studentCollection, addStudentCollectionQuestion, deleteStudentCollectionQuestion } from "@/api/individuationRead.js"
export default {
    name: 'EnglishWebIndex',
    components: {
        ReadingQuestion
    },
    data() {
        return {
            haveCollect: true,
            defaultStart: true,
            total: 0,
            drawer: false,
            paperData: {},
            readForm: {
                dataTime: [],
                source_type: 5,
                unit_id: null
            },
            paperDataList: [],
            // 快捷日期
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            // 单元数据
            elementOptions: [],
            currentPage: 4
        };
    },
    computed: {
        title() {
            switch (this.readForm.source_type) {
                case 5:
                    return "全部"
                case 1:
                    return "智能训练"
                case 2:
                    return "水平测试"
                default:
                    return "全部"
            }
        }
    },
    watch: {
        readForm: {
            async handler(nv) {
                this.currentPage = 1
                let { source_type, dataTime } = nv
                let start_time, end_time;
                console.log(nv);
                if (dataTime.length) {
                    start_time = dataTime[0]
                    end_time = dataTime[1]
                } else {
                    start_time, end_time = null
                }
                let mode = null;
                if (source_type == 1) {
                    mode = 0
                } else if (source_type == 2) {
                    mode = 1
                }
                let data = {
                    book_id: this.checkedBookData.book_id,
                    unit_id: null,
                    article_question_type: 5,
                    source: source_type,
                    category: null,
                    mode,
                    is_individ: 1,
                    end_time,
                    start_time
                }
                this.studentCollection(data)
            },
            deep: true
        }
    },
    mounted() {
        this.checkedBookData = JSON.parse(localStorage.getItem("bookData"))
        this.initStudentCollection()
    },

    methods: {
        readCollect() {
            console.log(this.paperData, "this.paperData");
            const { id, unit_id } = this.paperData
            let data = {
                question_type: null,
                unit_id,
                book_id: this.checkedBookData.book_id,
                source_type: null,
                link_id: id,
                source: null,
                is_individ: 1
            }
            this.$confirm('此操作将移除收藏并载入下一题, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }).then(async () => {
                await deleteStudentCollectionQuestion(data)
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                if (this.paperDataList.length == this.currentPage) {
                    this.currentPage -= 1
                }
                let { unit_id, source_type, dataTime } = this.readForm
                let start_time, end_time;
                if (dataTime.length) {
                    start_time = dataTime[0]
                    end_time = dataTime[1]
                } else {
                    start_time, end_time = null
                }
                let mode = null;
                if (source_type == 1) {
                    mode = 0
                } else if (source_type == 2) {
                    mode = 1
                }
                let testData = {
                    book_id: this.checkedBookData.book_id,
                    unit_id,
                    article_question_type: 5,
                    source: source_type,
                    category: null,
                    mode,
                    is_individ: 1,
                    end_time,
                    start_time
                }
                this.studentCollection(testData)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消操作'
                });
            });

        },
        initStudentCollection() {
            let data = {
                book_id: this.checkedBookData.book_id,
                unit_id: null,
                article_question_type: 5,
                source: 5,
                category: null,
                mode: null,
                is_individ: 1
            }
            this.studentCollection(data)
        },
        async studentCollection(data) {
            const res = await studentCollection(data)
            this.paperDataList = res.data["0"].filter(item => item != null)
            this.total = this.paperDataList.length
            if (!this.total) {
                this.haveCollect = false
                return
            } else {
                this.haveCollect = true
            }
            this.currentPage = 1
            this.disposepaperData(this.paperDataList[this.currentPage - 1])
        },
        disposepaperData(data) {
            this.paperData = {
                unit_id: data.unit_id,
                title: data.title,
                type: data.type,
                id: data.id,
                isAnswer: false,
                questionList: data.article_question_answer_info_list.map(
                    (question) => {
                        let newTitle = question.title;
                        if (data.type == 5) {
                            if (question.answer_type == 2) {
                                newTitle = "_____";
                            } else {
                                newTitle = "";
                            }
                        }
                        if (question.answer_type == 2) {
                            let index = 1;
                            let pos = newTitle.indexOf("_____");
                            while (pos !== -1) {
                                newTitle = newTitle.replace(
                                    /_{5}/,
                                    ` <input class='question-input' autocomplete="off" id='input-${question.question_id}-${index}' onpaste = "return false";></input> `
                                );
                                index++;
                                pos = newTitle.indexOf("_____");
                            }
                            question.inputNum = index - 1;
                        }
                        let test = question.answers.map(item => {
                            item.answer_id = item.id
                            return item
                        })
                        return {
                            initTitle: question.title,
                            questionId: question.question_id,
                            title: newTitle,
                            answerType: question.answer_type,
                            parse: question.parse,
                            answerList: test,
                            studentAnswer: [],
                            inputNum: question.inputNum,
                        };
                    }
                ),
            };
        },
        submitPaper() {
            let number = 0;
            this.paperData.questionList.forEach((item) => {
                if (item.answerType == 2) {
                    item.studentAnswer = [];
                    for (let i = 1; i <= item.inputNum; i++) {
                        let inputDom = document.getElementById(
                            `input-${item.questionId}-${i}`
                        );
                        item.studentAnswer.push(inputDom.value.trim());
                    }
                }
                if (!item.studentAnswer || item.studentAnswer.length == 0) {
                    number++;
                }
            });
            this.$confirm(
                `${number > 0 ? "还有" + number + "道题未答，" : ""}
        是否检查完毕，确认提交？`,
                "提示",
                {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                }
            )
                .then(() => {
                    this.verifyAnswer();
                })
                .catch(() => {
                    return false;
                });
        },
        verifyAnswer() {
            this.paperData.isAnswer = true
            this.paperData.questionList = this.paperData.questionList.map(item => {
                item.title = item.initTitle
                let studentAnswerQuestion = item.answerList.filter(item1 => {
                    if (item.answerType == 2) {
                        return item.studentAnswer[0] == item1.answer
                    } else {
                        return item1.id == item.studentAnswer[0]
                    }
                })
                if (item.answerType == 2 && studentAnswerQuestion.length <= 0) {
                    const answer = item.studentAnswer[0]
                    const { answer_id } = item.answerList[0].answer_id
                    item.verifyAnswer = [{
                        is_true: 0,
                        answer,
                        answer_id
                    }]
                } else {
                    item.verifyAnswer = [...studentAnswerQuestion]
                }
                let studentTrueAnswer = item.answerList.filter(item1 => item1.is_true == 1)
                item.trueAnswer = [...studentTrueAnswer]
                if (studentAnswerQuestion.length <= 0) {
                    item.isTrue = 0
                    return item
                }
                if (studentAnswerQuestion[0].answer_id == studentTrueAnswer[0].answer_id) {
                    item.isTrue = true
                } else {
                    item.isTrue = false
                }
                return item
            })
            console.log(this.paperData, "this.paperData");
        },
        nextQuestion() {
            const flag = this.currentPage + 1
            this.currentPage+=1
            if (flag > this.paperDataList.length) {
                this.$confirm('当前为最后一道收藏题目, 是否跳转到第一道?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }).then(() => {
                    this.currentPage=1
                    this.disposepaperData(this.paperDataList[this.currentPage-1])
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
                return
            }
            this.disposepaperData(this.paperDataList[this.currentPage - 1])
        },
        openDrawer() {
            this.drawer = true
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
             this.currentPage = val
            this.disposepaperData(this.paperDataList[this.currentPage - 1])
        }
    },
};
</script>

<style lang="scss" scoped>
.collectRead {
    .mosk-btn {
        border-bottom-left-radius: 6px;
        border-top-left-radius: 6px;
        position: fixed;
        top: 40%;
        right: 0;
        font-size: 16px;
        letter-spacing: 4px;
        padding: 10px 5px;
        writing-mode: vertical-rl;
        background: $color-main;
        color: aliceblue;
    }

    /deep/ .el-drawer__wrapper {
        pointer-events: none;
    }

    /deep/ .el-drawer.rtl {
        pointer-events: all;
    }

    /deep/ .el-drawer {
        width: 350px !important;
    }

    .el-drawer__body {
        position: relative;
        top: 0;
        left: 0;

        .mosk-drawer-close {
            position: absolute;
            top: 50%;
            left: 0;
            transform: translateY(-50%);
            font-size: 30px;
            padding: 8px 0;
            background: rgb(189, 188, 188);
            color: #f1f0f0;
        }
    }

    /deep/ .el-radio-button__inner {
        padding: 6px 5px !important;
    }

    /deep/ .el-input__inner {
        width: 200px;
        height: 30px;
        line-height: 30px;
        padding: 3px 5px;
    }

    /deep/ .el-date-editor .el-range-separator {
        line-height: 22px;
    }

    /deep/ .el-date-editor .el-range__icon {
        line-height: 22px;
    }

    /deep/ .el-input__icon {
        display: none;
    }

}
</style>